import 'package:flutter/material.dart';

/// 渐变动画
/// END
class FadeAnimatedContent extends StatefulWidget {
  final Widget child;
  final bool show; // 动画显示状态
  final int duration; // 动画时长
  const FadeAnimatedContent({
    Key? key,
    required this.child,
    this.show = false,
    this.duration = 300,
  }) : super(key: key);

  @override
  FadeAnimatedContentState createState() => FadeAnimatedContentState();
}

class FadeAnimatedContentState extends State<FadeAnimatedContent>
    with TickerProviderStateMixin {
  late AnimationController animationController;
  late Animation<double> animation;

  @override
  void initState() {
    animationController = new AnimationController(
      vsync: this,
      duration: Duration(
        milliseconds: widget.duration,
      ),
    );
    animation = Tween(begin: 0.0, end: 1.0)
        .chain(CurveTween(curve: Curves.easeIn))
        .animate(animationController);

    if (widget.show) {
      animationController.forward();
    }
    super.initState();
  }

  @override
  void didUpdateWidget(FadeAnimatedContent oldWidget) {
    if (widget != oldWidget) {
      if (widget.show && !oldWidget.show) {
        animationController.forward(from: 0.0);
      } else if (!widget.show) {
        animationController.reverse();
      }
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return FadeTransition(
      opacity: animation,
      child: widget.child,
    );
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }
}
